import 'package:cached_network_image/cached_network_image.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';

final networkUriReg = RegExp('^http');
final localUriReg = RegExp('^assets/');

class CommonImage extends StatelessWidget {
  final String? src;
  final double? width;
  final double? height;
  final BoxFit? fit;
  final bool? isCircle;

  const CommonImage(
    this.src, {
    super.key,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.isCircle = false,
  });

  @override
  Widget build(BuildContext context) {
    Widget? img;
    if (TextUtil.isEmpty(src)) {
      img = Container();
    }
    if (networkUriReg.hasMatch(src!)) {
      img = CachedNetworkImage(
        imageUrl: src!,
        width: width,
        height: height,
        fit: fit,
        placeholder: (context, url) => const CircularProgressIndicator(),
        errorWidget: (context, url, error) => const Icon(Icons.error),
      );
    }
    if (localUriReg.hasMatch(src!)) {
      img = Image.asset(
        src!,
        width: width,
        height: height,
        fit: fit,
      );
    }
    if (img != null) {
      return isCircle!
          ? ClipOval(
              child: img,
            )
          : img;
    }
    assert(false, '图片地址 src 不合法');
    return Container();
  }
}
